package com.youxin.cpcenter.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.common.qiniu.QiniuBucketType;
import com.youxin.cpcenter.service.UploadService;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.ObjectUtils;

/**
 * 上传控制器
 * 
 * @author yingde.cao
 *
 */
@RestController
@RequestMapping
public class UploadController extends BaseController {
	@Autowired
	private UploadService uploadService;
	
	@RequestMapping(value = "/api/upload/commission", method = RequestMethod.POST)
	@ResponseBody
	public ResponseObject uploadCommissionFile(@RequestParam(value = "file", required = true) MultipartFile file) 
	{		
		return upload(file, QiniuBucketType.CpDelegate);
	}
	
	@RequestMapping(value = "/api/upload/idcard", method = RequestMethod.POST)
	@ResponseBody
	public ResponseObject uploadIdCard(@RequestParam(value = "file", required = true) MultipartFile file) 
	{		
		return upload(file, QiniuBucketType.CpIdCard);
	}
	
	@RequestMapping(value = "/api/upload/license", method = RequestMethod.POST)
	@ResponseBody
	public ResponseObject uploadLicense(@RequestParam(value = "file", required = true) MultipartFile file) 
	{		
		return upload(file, QiniuBucketType.CpBusinessLicense);
	}

	public ResponseObject upload(MultipartFile file,QiniuBucketType bucketType) {
		try {
			ObjectUtils.requestNonNull(file,"文件不能为空");
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			fileName = FilenameUtils.getBaseName(fileName) + "_" + KeyGenerationUtils.generateKey() + "."
					+ FilenameUtils.getExtension(fileName);
			// File fileToSave = new File(file.getOriginalFilename());
			// FileCopyUtils.copy(bytes, fileToSave);
			String result = uploadService.upload(bucketType.getName(), bytes, fileName);
			String urlString = bucketType.getUrl() + result;
			return ResponseObject.successObject(urlString);
		} catch (Exception e) {
			return ResponseObject.systemError(e);
		}
	}

}
